<template>
  <div v-if="goodsDetail">
    <!-- 导航栏 -->
    <van-nav-bar
      :title="goodsDetail.proname"
      left-arrow
      @click-left="onClickLeft"
    />
    <!-- 轮播图渲染 -->
    <van-swipe class="my-swipe" :autoplay="3000" indicator-color="white">
      <van-swipe-item
        v-for="(item, index) in goodsDetail.banners[0].split(',')"
        :key="index"
      >
        <img style="width: 100%" :src="item" />
      </van-swipe-item>
    </van-swipe>
    <!-- 详情信息 -->
    <div class="info">
      <p>
        <van-tag size="large" type="danger" style="margin-right: 5px"
          >自营</van-tag
        >
        {{ goodsDetail.proname }}
      </p>
      <p class="price">￥{{ formatPrice(goodsDetail.originprice) }}</p>
    </div>
    <van-action-bar>
      <van-action-bar-icon icon="chat-o" text="客服" />
      <van-action-bar-icon
        icon="cart-o"
        text="购物车"
        v-if="cartStore.getTotalCount() > 0"
        :badge="cartStore.getTotalCount()"
        @click="$router.replace('/cart')"
      />
      <van-action-bar-icon
        icon="cart-o"
        text="购物车"
        v-else
        @click="$router.replace('/cart')"
      />
      <van-action-bar-icon icon="shop-o" text="店铺" />
      <van-action-bar-button type="warning" @click="add" text="加入购物车" />
      <van-action-bar-button type="danger" text="立即购买" />
    </van-action-bar>
  </div>
</template>

<script setup>
import { ref } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { getGoodsDetail } from '@/api/goods'
import { useCartStore } from '@/store/modules/cart'
const route = useRoute()
const router = useRouter()
const cartStore = useCartStore()
const goodsDetail = ref(null)

const getGoodsDetailData = async () => {
  const res = await getGoodsDetail(route.query.proid)
  goodsDetail.value = res.data
}

const onClickLeft = () => {
  router.back()
}

getGoodsDetailData()

// 格式化金额
const formatPrice = price => {
  return price.toFixed(2)
}

// 加入购物车
const add = () => {
  const goods = {
    proid: goodsDetail.value.proid,
    proname: goodsDetail.value.proname,
    img: goodsDetail.value.img1,
    number: 1,
    price: goodsDetail.value.originprice,
    state: true
  }

  cartStore.addToCart(goods)
}
</script>

<style lang="scss" scoped>
.info {
  padding: 10px;
  padding-bottom: 50px;
  .price {
    font-size: 20px;
    color: red;
    font-weight: bold;
  }
}
</style>
